package com.lincoln.framework.controller.sys;

import com.lincoln.framework.annotation.MenuAuth;
import com.lincoln.framework.entity.SysAuthorization;
import com.lincoln.framework.entity.SysMenu;
import com.lincoln.framework.entity.SysRole;
import com.lincoln.framework.exception.EntityNotFoundException;
import com.lincoln.framework.hibernate.Page;
import com.lincoln.framework.service.SysAuthorizationService;
import com.lincoln.framework.service.SysMenuService;
import com.lincoln.framework.service.SysRoleService;
import com.lincoln.framework.utils.StringUtilsEx;
import com.lincoln.framework.utils.WebParamUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 系统端角色controller
 * 
 * @author ssx
 */
@Controller
@RequestMapping("/sys/role")
public class RoleController extends SysBaseController<SysRole> {
	
	@Autowired
	private SysRoleService sysRoleService;
	
	@Autowired
	private SysMenuService sysMenuService;
	
	@Autowired
	private SysAuthorizationService sysAuthorizationService;
	
	private Page<SysRole> sysRolePage;
	
	private List<SysMenu> sysMenuList;
	
	private SysRole sysRole;
	
	private int id;
	
	/**
	 * 跳转列表页面
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/toList.do")
	@MenuAuth(buttonRight = MenuAuth.MENU_BUTTON_1)
	public String toList(HttpServletRequest request, Model model) throws Exception {
		this.saveRequestParameter();
		sysRolePage = sysRoleService.findPage(this.saveQueryInfoAndReturnPage("desc", "id"));
		
		model.addAttribute("sysRolePage", sysRolePage);
		return "sys/role/role_list";
	}
	
	/**
	 * 跳转增加页面
	 * @param request
	 * @param model
	 * @return
	 * @throws EntityNotFoundException
	 */
	@RequestMapping("/toEdit.do")
	@MenuAuth(buttonRight = MenuAuth.MENU_BUTTON_2)
	public String toEdit(HttpServletRequest request, Model model) throws EntityNotFoundException {
		this.initSysRole(request, true);
		
		model.addAttribute("sysRole", sysRole);
		return "sys/role/role_edit";
	}
	
	/**
	 * 跳转编辑页面
	 * @param request
	 * @param model
	 * @return
	 * @throws EntityNotFoundException 
	 */
	@RequestMapping("/toConfig.do")
	@MenuAuth(buttonRight = MenuAuth.MENU_BUTTON_2)
	public String toConfig(HttpServletRequest request, Model model) throws EntityNotFoundException {
		this.initSysRole(request, false);
		sysMenuList = sysMenuService.findAllInTree();
		
		model.addAttribute("sysRole", sysRole);
		model.addAttribute("sysRoleList", sysRoleService.findAll());
		model.addAttribute("sysMenuList", sysMenuList);
		return "sys/role/role_config";
	}
	
	/**
	 * 根据角色id获取权限配置
	 * @param request
	 * @throws EntityNotFoundException 
	 */
	@ResponseBody
	@RequestMapping("/getAuthorizationByRoleId.do")
	@MenuAuth(buttonRight = MenuAuth.MENU_BUTTON_2)
	public void getAuthorizationByRoleId(HttpServletRequest request) throws EntityNotFoundException {
		this.initSysRole(request, false);
		this.setAttributes("authorizationCode", sysRole.getAuthorizationCode());
		this.returnSuccess();
	}
	
	/**
	 * 保存新增角色
	 * @param request
	 * @throws EntityNotFoundException 
	 */
	@ResponseBody
	@RequestMapping("/saveNewRole.do")
	@MenuAuth(buttonRight = MenuAuth.MENU_BUTTON_2)
	public void saveRole(HttpServletRequest request) throws EntityNotFoundException {
		int roleId = WebParamUtils.getIntParameter(request, "id");
		String roleName = request.getParameter("roleName");
		
		if (sysRoleService.checkExistByName(roleId, roleName)) {
			this.returnError("角色名称已存在", false);
			return;
		}
		
		this.initSysRole(request, true);
		sysRole.setName(roleName);
		sysRole.setRemark(request.getParameter("roleRemark"));
		
		sysRoleService.saveSysRole(sysRole);
		this.addSysAdminLog((roleId > 0 ? "修改" : "新增") + "角色");
		this.returnSuccess("保存成功");
	}
	
	/**
	 * 保存角色配置
	 * @param request
	 * @throws EntityNotFoundException 
	 */
	@ResponseBody
	@RequestMapping("/saveRoleConfig.do")
	@MenuAuth(buttonRight = MenuAuth.MENU_BUTTON_2)
	public void saveRoleConfig(HttpServletRequest request) throws EntityNotFoundException {
		this.initSysRole(request, true);
		
		String[] menuIds = request.getParameterValues("menuId");
		String[] modules = request.getParameterValues("module");
		
		List<SysAuthorization> oldSysAuthorizationList = sysRole.getAuthorizations();
		sysRole.setAuthorizations(null);
		sysAuthorizationService.deleteSysAuthorizationList(oldSysAuthorizationList);
		
		this.formatSysRoleAuth(menuIds, modules);
		sysRoleService.saveSysRole(sysRole);
		this.addSysAdminLog("配置角色权限");
		
		this.returnSuccess("保存成功");
	}
	
	/**
	 * 删除
	 * @param request
	 * @throws EntityNotFoundException 
	 */
	@ResponseBody
	@RequestMapping("/delete.do")
	@MenuAuth(buttonRight = MenuAuth.MENU_BUTTON_3)
	public void delete(HttpServletRequest request) throws EntityNotFoundException {
		this.initSysRole(request, false);
		
		sysRoleService.deleteSysRole(sysRole);
		this.addSysAdminLog("删除角色");
		this.returnSuccess("删除成功");
	}
	
	/**
	 * 初始化系统菜单对象
	 * @param request
	 * @param needInitial
	 * @throws EntityNotFoundException
	 */
	private void initSysRole(HttpServletRequest request, boolean needInitial) throws EntityNotFoundException {
		id = WebParamUtils.getIntParameter(request, "id");
		
		if (id == 0 && needInitial) {
			sysRole = new SysRole();
			return;
		}
		
		sysRole = sysRoleService.getSysRoleById(id);
		if (sysRole == null) {
			throw new EntityNotFoundException("系统角色不存在");
		}
	}
	
	/**
	 * 解析页面传过来的菜单模块功能集
	 * @param menuIds	菜单id数组
	 * @param modules	模块数组，元素结构为（菜单id_模块id，如5_1）
	 */
	private void formatSysRoleAuth(String[] menuIds, String[] modules){
		List<SysAuthorization> sysAuthorizationList = new ArrayList<SysAuthorization>();
		if (menuIds != null && menuIds.length > 0) {
			for (int i=0; i<menuIds.length; i++) {
				SysAuthorization sysAuthorization = new SysAuthorization();
				sysAuthorization.setSysRole(sysRole);
				
				SysMenu sysMenu = sysMenuService.getSysMenuById(Integer.parseInt(menuIds[i]));
				sysAuthorization.setSysMenu(sysMenu);
				
				Integer[] roleRights = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
				if (modules != null && modules.length > 0) {
					for (int j=0; j<modules.length; j++) {
						String[] moduleDivide = modules[j].split("_");
						if (moduleDivide[0].equals(menuIds[i])) {
							roleRights[Integer.parseInt(moduleDivide[1])-1] = 1;
						}
					}
				}
				
				sysAuthorization.setButtonRights(StringUtilsEx.join(roleRights, ","));
				sysAuthorizationList.add(sysAuthorization);
			}
		}
		sysRole.setAuthorizations(sysAuthorizationList);
	}
}
